package cn.b.sky.mes.qm.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.b.sky.mes.qm.model.QualityReport;
import cn.b.sky.mes.qm.model.StatisticData;
import cn.b.sky.mes.qm.model.condition.QualityReportCondition;
import cn.b.sky.mes.qm.service.QualityReportService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.common.file.Excel;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.qm.constants.QmConstant;

/**
 * <strong>Title : QualityReportController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.qm.controller<br></strong>
 * <strong>Description : </strong>质量报告控制器<br> 
 * <strong>Create on : 2015年12月21日 上午11:21:43<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/qualityReport/*")
public class QualityReportController extends SecurityController {
  public static final String MONTH = "MONTH";

  public static final String DAY = "DAY";

  @Resource
  QualityReportService qualityReportService;

  @RequestMapping("qualityDateReport")
  public String showQualityDateReport(Model model, HttpSession session, String navTabId,
      @ModelAttribute("condition") QualityReportCondition condition) throws ParseException {
    condition.setSiteCode(getSiteCode());
    condition.setReportType(DAY);
    session.setAttribute(QmConstant.QUALITY_DATE_REPORT, condition);
    setQueryDateRangeForPie(condition);//查询条件跟饼图同步
    List<QualityReport> list = qualityReportService.selectAllQualityReportList(condition);

    model.addAttribute("data", list);
    return "qm/qualityReport/qualityReport";
  }

  @RequestMapping("qualityMonthReport")
  public String showQualityMonthReport(Model model, String navTabId, HttpSession session,
      @ModelAttribute("condition") QualityReportCondition condition) throws ParseException {
    condition.setSiteCode(getSiteCode());
    condition.setReportType(MONTH);
    session.setAttribute(QmConstant.QUALITY_MONTH_REPORT, condition);
    SimpleDateFormat dfMonth = new SimpleDateFormat("yyyy-MM-dd");
    ArrayList<Date> endDateList = new ArrayList<Date>();
    Calendar calendar = Calendar.getInstance();
    for (int i = 0; i < 12; i++) {
      calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
      endDateList.add(dfMonth.parse(dfMonth.format(calendar.getTime())));
      calendar.add(Calendar.MONTH, -1);
    }
    setQueryDateRangeForPie(condition);//查询条件跟饼图同步
    List<QualityReport> list = qualityReportService.selectAllQualityReportList(condition);
    model.addAttribute("data", list);
    model.addAttribute("endDateList", endDateList);
    return "qm/qualityReport/qualityReport";
  }

  @RequestMapping("qualityReportForPie")
  @ResponseBody
  public DWZResult selectDefectLevelPie(String groupType, String navTabId, QualityReportCondition condition)
      throws ParseException {
    condition.setSiteCode(getSiteCode());
    condition.setChartType("pie");
    //新增订单档案饼图查询，如何订单号ProductionNum为空则是日报和月报
    if (StringUtils.isBlank(condition.getProductionNum())) {
      setQueryDateRangeForPie(condition);
    }

    // -1表示全部
    if ("-1".equals(condition.getWorkCenterCodeStr())) {
      condition.setWorkCenterCodeStr(null);
    }
    List<StatisticData> list = qualityReportService.selectListGroupByType(condition, groupType);
    Collections.sort(list);
    return ajaxDone(list);
  }

  @RequestMapping("qualityReportForLine")
  @ResponseBody
  public DWZResult qualityReportForLine(String groupType, String navTabId, QualityReportCondition condition)
      throws ParseException {
    condition.setSiteCode(getSiteCode());
    setQueryDateRange(condition);
    //group by groupType  and  createDateTime
    condition.setChartType("line");
    List<StatisticData> list = qualityReportService.selectListGroupByType(condition, groupType);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat dfMonth = new SimpleDateFormat("yyyy-MM");

    ArrayList<String> textArray = new ArrayList<String>();
    ArrayList<String> dateArray = new ArrayList<String>();

    Date startDate = condition.getStartDateTime();
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(startDate);

    if (MONTH.equals(condition.getReportType())) {
      //月报横坐标
      for (int i = 0; i < condition.getQuantity(); i++) {
        dateArray.add(dfMonth.format(startCal.getTime()));
        startCal.add(Calendar.MONTH, 1);
      }
    } else {
      //日报横坐标
      for (int i = 0; i < condition.getQuantity(); i++) {
        dateArray.add(df.format(startCal.getTime()));
        startCal.add(Calendar.DAY_OF_YEAR, 1);
      }
    }

    HashMap<String, Integer> map = new HashMap<String, Integer>();

    int quantity = condition.getQuantity();
    ArrayList<int[]> dataArray = new ArrayList<int[]>();
    Collections.sort(list);//按编号类型描述排序

    for (StatisticData data : list) {
      if (!map.containsKey(data.getCode())) {
        //存放对应编号的在dataArray的位置
        map.put(data.getCode(), map.size());

        //初始化该编号在所有日期的数量 为0
        int[] values = new int[quantity];
        dataArray.add(values);

        //存放编号类型描述
        textArray.add(data.getText());
      }
      int x = 0;
      Calendar createCal = Calendar.getInstance();
      startCal.setTime(startDate);
      if (MONTH.equals(condition.getReportType())) {
        createCal.setTime(dfMonth.parse(data.getCreateDateTime()));
        int year = createCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR);
        int month = createCal.get(Calendar.MONTH) - startCal.get(Calendar.MONTH);
        x = 12 * year + month;
      } else {
        createCal.setTime(df.parse(data.getCreateDateTime()));
        long oneday = 24 * 60 * 60 * 1000;
        long createTimeMills = createCal.getTime().getTime();
        long startTimeMills = startCal.getTime().getTime();
        x = (int) ((createTimeMills - startTimeMills) / oneday);
      }
      int y = map.get(data.getCode());
      dataArray.get(y)[x] = data.getCount();
    }

    HashMap<String, Object> chartData = new HashMap<String, Object>();

    chartData.put("textArray", textArray); //编号类型描述
    chartData.put("dateArray", dateArray);//日期横坐标
    chartData.put("dataArray", dataArray.toArray());//二维数组
    return ajaxDone(chartData);
  }

  private void setQueryDateRangeForPie(QualityReportCondition condition) throws ParseException {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    if (condition.getReportType().equals(MONTH)) {
      if (condition.getEndDateTime() == null) {
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
        condition.setEndDateTime(calendar.getTime()); //本月最后一天
      }
      condition.setEndDateTime(df.parse(df.format(condition.getEndDateTime())));//去除时分秒
      calendar.setTime(condition.getEndDateTime());
      calendar.set(Calendar.DATE, 1); //本月第一天
      condition.setStartDateTime(calendar.getTime());//起始日期月初
    } else {
      if (condition.getEndDateTime() == null) {
        condition.setEndDateTime(df.parse(df.format(new Date())));
      }
      condition.setStartDateTime(condition.getEndDateTime());
    }

  }

  private void setQueryDateRange(QualityReportCondition condition) throws ParseException {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    if (condition.getReportType().equals(MONTH)) {
      if (condition.getQuantity() == null) {
        condition.setQuantity(6);//默认六个月
      }
      if (condition.getEndDateTime() == null) {
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
        condition.setEndDateTime(calendar.getTime()); //本月最后一天
      }
      condition.setEndDateTime(df.parse(df.format(condition.getEndDateTime())));//去除时分秒
      calendar.setTime(condition.getEndDateTime());
      calendar.add(Calendar.MONTH, -condition.getQuantity() + 1);
      calendar.set(Calendar.DATE, 1); //当月月第一天
      condition.setStartDateTime(calendar.getTime());
    } else {
      if (condition.getQuantity() == null) {
        condition.setQuantity(7);//默认七天
      }
      if (condition.getEndDateTime() == null) {
        condition.setEndDateTime(df.parse(df.format(new Date())));
      }
      calendar.setTime(condition.getEndDateTime());
      long oneday = 24 * 60 * 60 * 1000;
      long timeMills = calendar.getTime().getTime();
      long startTimeMills = timeMills - oneday * (condition.getQuantity() - 1);
      calendar.setTimeInMillis(startTimeMills);
      condition.setStartDateTime(calendar.getTime());
    }

  }
  
  @RequestMapping("controlArchivesInspectForPie")
  @ResponseBody
  public DWZResult controlArchivesInspectForPie(String groupType, 
      String navTabId, QualityReportCondition condition)
      throws ParseException {
    if(!StringUtils.isBlank(condition.getControlNum())){
      condition.setSiteCode(getSiteCode());
      condition.setChartType("pie");
      List<StatisticData> list = qualityReportService.selectListGroupByType(condition, groupType);
      Collections.sort(list);
      return ajaxDone(list);
    }
      return ajaxDone(null); 
  }


  @RequestMapping(value = "exportDateReport")
  @ResponseBody
  public void exportDateReport(String imageMap, HttpSession session, QualityReportCondition condition,
      HttpServletResponse response, String tableMap, String arrangement) throws IOException {
    QualityReportCondition condition0 = (QualityReportCondition) session
        .getAttribute(QmConstant.QUALITY_DATE_REPORT);
    if (condition0 != null) {
      condition = condition0;
    }
    condition.setSiteCode(getSiteCode());
    List<Map<String, Object>> list = qualityReportService.selectAllQualityReportMapList(condition);

    Excel excel = new Excel();
    excel.setImageMap(imageMap);
    excel.setTableMap(tableMap);
    Map<String, List<Map<String, Object>>> tableListMap = new HashMap<String, List<Map<String, Object>>>();
    tableListMap.put("iTable", list);
    excel.autoAddModel(arrangement, tableListMap);

    /* 
     *  手动布局
     *  ExcelModel m=new GridModel(excel.getTable("iTable"), list);
        ExcelModel m1=new PictureModel(excel.getImgData("pie1"));
        excel.addExcelModel(m);
        excel.addExcelModel(m1, col, row);
        */

    excel.doExport(response, getImeViewMessageI18n(null, "qualityDateReport.C"));
  }

  @RequestMapping(value = "exportMonthReport")
  @ResponseBody
  public void exportMonthReport(String imageMap, String tableMap, HttpServletResponse response, HttpSession session,
      QualityReportCondition condition, String arrangement) throws IOException {

    QualityReportCondition condition0 = (QualityReportCondition) session
        .getAttribute(QmConstant.QUALITY_MONTH_REPORT);
    if (condition0 != null) {
      condition = condition0;
    }
    condition.setSiteCode(getSiteCode());
    List<Map<String, Object>> list = qualityReportService.selectAllQualityReportMapList(condition);

    Excel excel = new Excel();
    excel.setImageMap(imageMap);
    excel.setTableMap(tableMap);
    Map<String, List<Map<String, Object>>> tableListMap = new HashMap<String, List<Map<String, Object>>>();
    tableListMap.put("iTable", list);
    excel.autoAddModel(arrangement, tableListMap);

    excel.doExport(response,
        getImeViewMessageI18n(null, "qualityMonthReport.C"));
  }
}
